package com.cyb.beta.utils;


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 获取本机ip
 *
 * @author chenyongbo
 * @date 2016/6/24.
 */
public class IPUtils {
    public static List<String> getIpList() throws SocketException {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();

        List<String> ipList = new ArrayList<>();
        InetAddress ip;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            if (!netInterface.isUp() || netInterface.isLoopback()
                    || netInterface.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = addresses.nextElement();
                if (ip.isLoopbackAddress()) {
                    continue;
                }
                if (ip != null && ip instanceof Inet4Address) {
                    ipList.add(ip.getHostAddress());
                }
            }
        }

        return ipList;
    }

    public static String getSelfIP() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface current = interfaces.nextElement();
                if (!current.isUp() || current.isLoopback()
                        || current.isVirtual()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = current.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress current_addr = addresses.nextElement();
                    if (current_addr.isLoopbackAddress()) {
                        continue;
                    }
                    if (current_addr instanceof Inet4Address) {
                        return current_addr.getHostAddress();
                    }
                }
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }

        return "127.0.0.1";
    }

    public static void main(String[] args) throws SocketException {
        IPUtils.getIpList().stream().forEach(System.out::println);
    }
}
